package com.jin.webvideo.videoCache;

import com.jin.webvideo.service.ConfigService;
import com.jin.webvideo.util.consts.ConfigConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.io.File;
import java.util.Map;

@Component
public class CachesPropertites implements ServletContextAware {
    @Autowired
    private ConfigService configService;
    private int threadCount;
    private long cacheSize;
    private String location;
    private String prefix;
    private int allowFailure;
    public CachesPropertites(){
    }
    public String getLocation() {
        return location;
    }

    public String getPrefix() {
        return prefix;
    }

    public int getThreadCount() {
        return threadCount;
    }

    public long getCacheSize() {
        return cacheSize;
    }

    public String saveLocation(){
        return location;
    }

    public int getAllowFailure() {
        return allowFailure;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        Map<String,String> map = configService.configMapByGroupId(ConfigConst.CACHE_CONFIG);
        // 默认线程数为5
        threadCount = Integer.valueOf(map.getOrDefault("threadCount", "5").trim());
        // 数据库存储为MB,计算时使用B
        cacheSize = Long.valueOf(map.getOrDefault("size", "4096").trim())*1024*1024;
        // 存储位置
        location = map.getOrDefault("location", "").trim();
        // 映射路径前缀
        prefix = map.getOrDefault("prefix", "").trim();
        // 允许失败的万分比
        allowFailure = Integer.valueOf(map.getOrDefault("allowFailure", "0").trim());

        while (prefix.endsWith("/") && !prefix.isEmpty()){
            prefix = prefix.substring(0, prefix.length() - 1);
        }
        // 断言非空且存在
        Assert.isTrue(!location.isEmpty() && new File(location).exists(), "location is illegal argument");
        Assert.isTrue(!prefix.isEmpty(), "prefix is empty");
    }
}
